using Avalonia.BiliBili.Units;
using Avalonia.Controls;
using Avalonia.Extensions.Event;
using Avalonia.Interactivity;
using Bilibili.Common;
using Bilibili.Common.Log;
using Bilibili.Model.Parts;
using Bilibili.WebClient.Api;
using DynamicData;
using PCLUntils.Objects;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Windows
{
    public partial class ActivityWindow : WindowBase
    {
        private ActivityClient Client { get; }
        private int PageIndex { get; set; } = 1;
        private ObservableCollection<ActivityModel> Activities { get; }
        public ActivityWindow()
        {
            InitializeComponent();
            Client = new ActivityClient();
            Activities = new ObservableCollection<ActivityModel>();
        }
        protected override void AfterInitializeComponent()
        {
            listView.ItemsSource = Activities;
            listView.ItemClick += ListView_ItemClick;
            listView.ScrollEnd += ListView_ScrollEnd;
            RunOnUiThread(LoadData);
        }
        private void ListView_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickItem is ListBoxItem item && item.Content is ActivityModel activity)
                {
                    var url = activity.link;
                    Navigater.OpenWebView(url);
                }
            }
            catch { }
        }
        private void ListView_ScrollEnd(object? sender, RoutedEventArgs e)
        {
            PageIndex++;
            RunOnUiThread(LoadData);
        }
        private async Task LoadData()
        {
            try
            {
                var result = await Client.GetList(PageIndex);
                if (result.IsSuccess())
                {
                    var m = result.Data;
                    if (m.IsNotEmpty())
                    {
                        var list = m.list.Where(x => x.link.Length != 0).ToList();
                        Activities.AddRange(list);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadData", ex);
            }
        }
    }
}